/**
 * 父子组件通信
 * 1. 父组件向子组件传值
 * 2. 子组件向父组件传值 ref.values 父组件传入获取子组件值的方法
 * 3. 父组件向子组件传方法
 * 4. 子组件向父组件传方法
 *
 * 改为：输入用户名 => 跳转到改用户匹配的类型
 * 用户数据从后端获取，先写假数据
 */

import { useState, useRef } from 'react'
import { Button, Input } from 'tdesign-react'
import KeepAlive from 'react-activation'
import { useTranslation } from 'react-i18next'
import Leader from './Leader'
import Customer from './Customer'

import './index.less'

type PropsType = {}

const ComponentsCommunication = (props: PropsType) => {

  const userList: UserType[] = [
    {
      userName: 'qingzi',
      userId: '1',
      userAge: 20,
      userRank: 'leader',
      userSex: 0,
    },
    {
      userName: 'lijia',
      userId: '2',
      userAge: 20,
      userRank: 'customer',
      userSex: 1,
    }
  ]

  const { t } = useTranslation(['webGames'])

  const [inputValue, setInputValue] = useState('')
  const [currentUser, setCurrentUser] = useState<UserType>(userList[0])


  const onUserInputChange = (e: any) => {
    setInputValue(e)
  }

  const onsubmitButton = () => {
    for (let userIndex = 0, userLen = userList.length; userIndex < userLen; userIndex++) {
      if (userList[userIndex].userName.includes(inputValue) || userList[userIndex].userId.includes(inputValue)) {
        setCurrentUser(userList[userIndex])
        break
      }
    }
  }

  return <div className='components-communication'>
    <div className='input-block'>
      <Input onChange={onUserInputChange} placeholder={t('practice.componentsCommunication.inputPlaceholder')}/>
      <Button onClick={onsubmitButton} className='submit-button'>{t('practice.componentsCommunication.goButton')}</Button>
    </div>
    <br/>
    {currentUser && <div className='user-tip'>
      {`${t('practice.componentsCommunication.currentRole')}: ${currentUser?.userName}`}
    </div>}
    {currentUser?.userRank === 'leader' && <Leader userName={currentUser.userName} />}
    {currentUser?.userRank === 'customer' && <Customer userName={currentUser.userName} />}
  </div>
}

const KeepAliveComponent = () => {
  return <KeepAlive key='components-communication' name='components-communication'>
    <ComponentsCommunication />
  </KeepAlive>
}


export default KeepAliveComponent
